package com.tyao.note.service;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.tyao.note.mapper.BNoteMapper;
import com.tyao.note.mapper.BTagMapper;
import com.tyao.note.mapper.TSRoleUserMapper;
import com.tyao.note.mapper.TSUserMapper;
import com.tyao.note.mapper.TULoginMapper;
import com.tyao.note.model.TSRole;
import com.tyao.note.model.TSUser;
import com.tyao.note.model.TULogin;
import com.tyao.note.service.exception.PasswordNotMatchException;
import com.tyao.note.service.exception.UserNotFoundException;
import com.tyao.note.service.exception.UserStatusException;
import com.tyao.note.service.exception.UsernameAlreadyExistException;

/**
 * 用户登录业务层
 * 
 * @author Ty-user1
 *
 */
@Service
public class UserService {

	@Autowired
	private TSUserMapper userMapper;
	@Autowired
	private TSRoleUserMapper tsRoleUserMapper;
	// 密码加盐
	@Value("#{messageConfig.salt}")
	private String salt;
	@Autowired
	private TULoginMapper loginMapper;
	@Autowired
	private BNoteMapper bNoteMapper;
	@Autowired
	private BTagMapper bTagMapper;

	/**
	 * 登录验证
	 * 
	 * @param username
	 * @param password
	 * @return user对象
	 * @throws UserNotFoundException
	 * @throws PasswordNotMatchException
	 */
	public TSUser login(String username, String password) throws Exception {
		TSUser user = userMapper.selectUserByUsername(username);
		if (user != null) {// 如果不是空，用户存在
			if (user.getState() == 1) {// 如果用户状态是已停用
				throw new UserStatusException("用户状态异常，请联系管理员!");
			} else {// 如果正常，执行以下操作
				password = DigestUtils.md5Hex(password + salt);
				if (user.getPassword().equals(password)) {// 判断数据库密码与输入密码是否一致
					return user;
				} else {
					throw new PasswordNotMatchException("密码不匹配");
				}
			}
		} else {// 如果是空，用户不存在
			throw new UserNotFoundException("用户不存在");
		}
	}

	/**
	 * 根据id查询用户
	 * 
	 * @param id
	 * @return
	 */
	public TSUser getTsUserById(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}

	/**
	 * 获取所有用户信息
	 * 
	 * @return 用户信息集合
	 */
	public List<TSUser> getAllUser() {
		List<TSUser> users = userMapper.selectAll();
		for (TSUser tsUser : users) {
			TSRole tsRole = getRoleByUserId(tsUser.getId());
			tsUser.setTsRole(tsRole);
		}
		return users;
	}

	/**
	 * 根据用户id查询角色信息
	 * 
	 * @param id
	 * @return
	 */
	public TSRole getRoleByUserId(Integer id) {
		return tsRoleUserMapper.selectRoleByUserId(id);
	}

	/**
	 * 修改用户信息，不包括密码
	 * 
	 * @param gender
	 * @param phone
	 * @param email
	 * @param remark
	 * @param id
	 */
	public TSUser updateUser(String gender, String phone, String email, String remark, Integer id) {
		TSUser user = new TSUser();
		user.setId(id);
		user.setGender(gender);
		user.setPhone(phone);
		user.setEmail(email);
		user.setRemark(remark);
		userMapper.updateByPrimaryKey(user);
		TSUser user2 = userMapper.selectByPrimaryKey(id);
		TSRole tsRole = getRoleByUserId(id);
		user2.setTsRole(tsRole);
		return user2;
	}

	/**
	 * 修改密码
	 * 
	 * @param newPwd
	 * @param id
	 * @throws PasswordNotMatchException
	 */
	public void changePassword(String oldPwd, String newPwd, Integer id) throws PasswordNotMatchException {
		TSUser user = getTsUserById(id);
		// md5加密
		oldPwd = DigestUtils.md5Hex(oldPwd + salt);
		// 数据库中取出密码做比较
		boolean flag = user.getPassword().equals(oldPwd);
		if (flag) {// 如果是true
			newPwd = DigestUtils.md5Hex(newPwd + salt);
			user.setPassword(newPwd);
			// 执行修改密码的方法
			userMapper.updateByPrimaryKey(user);
		} else {
			throw new PasswordNotMatchException("旧密码输入错误！");
		}
	}

	/**
	 * 管理员添加用户
	 * 
	 * @param username
	 * @param password
	 * @param gender
	 * @param phone
	 * @param email
	 * @param remark
	 * @throws UsernameAlreadyExistException
	 */
	public void addUser(String username, String password, String gender, String phone, String email, String remark)
			throws UsernameAlreadyExistException {
		TSUser user = userMapper.selectUserByUsername(username);// 查询 用户名是否存在
		if (user == null) {
			TSUser record = new TSUser();
			record.setUsername(username);
			// md5加密
			password = DigestUtils.md5Hex(password + salt);
			record.setPassword(password);
			record.setGender(gender);
			record.setPhone(phone);
			record.setEmail(email);
			record.setRemark(remark);
			// 插入用户,返回用户id
			userMapper.insert(record);
			long id = record.getId();
			// 根据返回的用户id插入用户角色信息
			tsRoleUserMapper.insert(id);
		} else {
			throw new UsernameAlreadyExistException("用户名已经存在！");
		}
	}

	/**
	 * 批量删除用户,同时删除用户角色信息
	 * 
	 * @param ids
	 */
	public void deleteBatchById(Integer[] ids) {
		userMapper.deleteBatch(ids);
		for (int id : ids) {
			// 删除角色信息
			tsRoleUserMapper.deleteByUserId((long) id);
			// 删除笔记
			bNoteMapper.deleteNoteByUserId(id);
			// 删除标签
			bTagMapper.deleteTagsByUserId(id);
			// 删除登录信息等...
			loginMapper.deleteLoginInfoByUserId((long) id);
		}
	}

	/**
	 * 根据id修改状态
	 * 
	 * @param id
	 */
	public void updateState(Integer id) {
		userMapper.updateState(id);
	}

	/**
	 * 根据条件查询结果
	 * 
	 * @param beginTime
	 * @param endTime
	 * @param search
	 * @return
	 */
	public List<TSUser> searchByInputText(String beginTime, String endTime, String search) {
		List<TSUser> users = userMapper.searchUser(beginTime, endTime, search);
		for (TSUser tsUser : users) {
			TSRole tsRole = getRoleByUserId(tsUser.getId());
			tsUser.setTsRole(tsRole);
		}
		return users;
	}

	/**
	 * 根据用户id查询用户登陆信息，如ip，上次登陆时间等
	 * 
	 * @param userId
	 * @return
	 */
	public TULogin loginInfo(int userId) {
		return loginMapper.selectByUser(userId);
	}

	/**
	 * 更新登陆ip，时间等信息
	 * 
	 * @param record
	 * @return
	 */
	public int updateLoginInfo(TULogin record) {
		return loginMapper.updateByPrimaryKey(record);
	}

	/**
	 * 插入登陆ip，时间等信息
	 * 
	 * @param record
	 * @return
	 */
	public int insertLoginInfo(TULogin record) {
		return loginMapper.insert(record);
	}

	/**
	 * 重置密码
	 * 
	 * @param id
	 * @return
	 * @throws UserStatusException
	 */
	public boolean resetUserPassword(Integer id) throws UserStatusException {
		TSUser tsUser = userMapper.selectByPrimaryKey(id);
		if (tsUser.getState() == 1) {
			throw new UserStatusException("用户状态异常");
		} else {
			String password = DigestUtils.md5Hex("123456789"+salt);
			// 修改成功返回true
			return userMapper.resetUserPassword(password,id) > 0 ? true : false;
		}
	}
	
	/**
	 * 确认管理员密码
	 * @param password
	 * @return
	 * @throws PasswordNotMatchException
	 */
	public boolean confirmAdminPassword(String password) throws PasswordNotMatchException {
		password = DigestUtils.md5Hex(password+salt);
		int index = userMapper.confirmAdminPassword(password);
		if (index>0) {
			return true;
		}else {
			throw new PasswordNotMatchException("管理员密码不匹配");
		}
	}
}
